<script setup>
// 引入图标
import { ShoppingCartFull, CircleCloseFilled } from '@element-plus/icons-vue'
import { computed } from 'vue'
// 引入仓库
import { useShopcart, useUser } from '@/stores/index'
// 引入删除购物车商品接口
import { DelShopCartService, UpdateNumShopCartService } from '@/api/shopcart'
// 创建仓库实例
const shopcartStore = useShopcart()
const userStore = useUser()

// 获取商品总数量
const totalNum = computed(() => {
  return shopcartStore.shopcartList.reduce((sum, item) => sum + item.num, 0)
})

// 选中数量
let ckNum = computed(() => {
  return shopcartStore.shopcartList.filter(r => r.state).reduce((a, b) => a + b.num, 0)
})

// 选择的商品总价
let total_Price = computed(() => {
  return shopcartStore.shopcartList.filter(r => r.state).reduce((a, b) => a + b.goods.price * b.num, 0)
})

// 全选
let ckAll = computed({
  get() {
    return shopcartStore.shopcartList.every(r => r.state)
  },
  set(val) {
    shopcartStore.shopcartList.forEach(r => r.state = val)
  }
})

// 删除购物车方法
const delShopCart = async (userId, goodsId) => {
  shopcartStore.delShoppingCart(userId, goodsId)
  const { data } = await DelShopCartService(userId, goodsId)
  if (data.success) {
    ElNotification({
      title: '通知',
      message: data.message,
      type: 'success',
    })
  } else {
    ElNotification({
      title: '通知',
      message: data.message,
      type: 'error',
    })
  }
}

// 监听到数据变化后，更新购物车数量
const changeNum = async (num, goodsId) => {
  await UpdateNumShopCartService({
    userId: userStore.user.user_id,
    goodsId,
    num
  })
}

// 结算
let buy = async () => {
  // 获取需要结算的商品数组
  let goods = shopcartStore.shopcartList.filter(r => r.state)
  if (goods.length === 0) {
    ElNotification({
      title: '通知',
      message: '请选择需要结算的商品',
      type: 'warning',
    })
    return
  }
  // console.log("查看商品");
  // console.log(goods);

  //删除购物车信息
  // 获取用户id
  let uid = userStore.user.user_id;
  var pids = [];
  for (var i = 0; i < goods.length; i++) {
    pids[i] = goods[i].goodsId
  }
  console.log(pids);
  let ids = pids.join(",");  //  id1,id2,id3

  //去支付
  let url = "http://47.100.94.241:8080/pay/alipay?userId=" + uid + "&ids=" + ids + "&orderNo=" + new Date().getTime() + "&orderName=" + userStore.user.userName + "的订单&totalPrice=" + shopcartStore.shopcartList.filter(r => r.state).reduce((sum, item) => sum + item.goods.price * item.num, 0);
  // 跳转页面
  location.href = url

  // 重新加载购物车
  shopcartStore.loadShopcartList()
}

</script>

<template>
  <div class="page">
    <div class="shopping-header">
      <div class="content">
        <p>
          <el-icon color="#ff6700" size="28">
            <ShoppingCartFull />
          </el-icon>
          &nbsp;我的购物车
        </p>
        <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
      </div>
    </div>
    <div class="shopping-content">
      <ul>
        <li class="content-header">
          <div class="pro-check">
            <el-checkbox v-model="ckAll" label="全选" size="large" />
          </div>
          <div class="pro-img"></div>
          <div class="pro-name">商品名称</div>
          <div class="pro-price">单价</div>
          <div class="pro-num">数量</div>
          <div class="pro-total">小计</div>
          <div class="pro-action">操作</div>
        </li>
        <li class="product-list" v-for="(pro) in shopcartStore.shopcartList" :key="pro.goodsId">
          <div class="pro-check">
            <el-checkbox v-model="pro.state" label="" size="large" />
          </div>
          <div class="pro-img">
            <img :src="pro.goods.goodsImg" alt="">
          </div>
          <div class="pro-name">{{pro.goods.goodsName}}</div>
          <div class="pro-price">{{pro.goods.price}}元</div>
          <div class="pro-num">
            <el-input-number @change="(num)=>{changeNum(num,pro.goodsId)}" v-model="pro.num" :min="1" :max="99" size="small" />
          </div>
          <div class="pro-total pro-total-in">{{pro.goods.price * pro.num}}元</div>
          <div class="pro-action">
            <el-popconfirm width="150px" title="确定删除吗？" confirm-button-text="确定" cancel-button-text="取消" @confirm="delShopCart(pro.userId,pro.goodsId)">
              <template #reference>
                <el-icon size="18">
                  <CircleCloseFilled />
                </el-icon>
              </template>
            </el-popconfirm>
          </div>
        </li>
      </ul>
      <div style="height: 20px; background-color: rgb(245, 245, 245);"></div>
      <div class="cart-bar">
        <div class="cart-bar-left">
          <span>
            <router-link to="/goods">继续购物</router-link>
          </span>
          <span class="sep">|</span>
          <span class="cart-total">
            共 <span class="cart-total-num">{{totalNum}}</span> 件商品，已选择 <span class="cart-total-num">{{ckNum}}</span> 件
          </span>
        </div>
        <div class="cart-bar-right">
          <span>
            <span class="total-price-title">合计：</span>
            <span class="total-price">{{total_Price}}元</span>
          </span>
          <el-popconfirm width="150px" title="确定购买吗？" confirm-button-text="确定" cancel-button-text="取消" @confirm="buy">
            <template #reference>
              <button class="btn-primary" :class="{'btn-primary-disabled':ckNum === 0 }" :disabled="ckNum === 0">去结算</button>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </div>
    <div class="mb20"></div>
  </div>
</template>

<style lang="less" scoped>
.shopping-header {
  height: 84px;
  border-bottom: 2px solid #ff6700;
  background-color: #fff;
  margin-bottom: 20px;
  .content {
    width: 1226px;
    margin: 0 auto;
    display: flex;
    p {
      font-size: 28px;
      line-height: 58px;
      display: flex;
      align-items: center;
      font-weight: 400;
      color: #424242;
    }
    span {
      color: #757575;
      font-size: 12px;
      height: 20px;
      line-height: 20px;
      margin-top: 30px;
      margin-left: 15px;
    }
  }
}
.shopping-content {
  width: 1226px;
  margin: 0 auto;
  background-color: #fff;
  .pro-check {
    width: 110px;
    text-align: center;
  }
  .pro-img {
    height: 85px;
    width: 120px;
    img {
      height: 80px;
      width: 80px;
    }
  }
  .pro-name {
    width: 380px;
  }
  .pro-price {
    width: 140px;
    padding-right: 18px;
    text-align: center;
  }
  .pro-num {
    width: 150px;
    text-align: center;
  }
  .pro-total {
    width: 200px;
    padding-right: 81px;
    text-align: right;
  }
  .pro-total-in {
    color: #ff6700;
  }
  .pro-action {
    width: 80px;
    text-align: center;
    &:hover {
      color: #ff6700;
    }
  }
  .content-header {
    height: 85px;
    padding-right: 26px;
    color: #424242;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #b0b0b0;
  }
  .product-list {
    height: 116px;
    padding: 15px 26px 15px 0;
    border-top: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
  }
  .cart-bar {
    width: 1226px;
    height: 50px;
    line-height: 50px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    .cart-bar-left {
      a {
        line-height: 50px;
        margin-left: 32px;
        color: #757575;
        &:hover {
          color: #ff6700;
        }
      }
      .sep {
        color: #eee;
        margin: 0 20px;
      }
      .cart-total {
        color: #757575;
        .cart-total-num {
          color: #ff6700;
        }
      }
    }
    .cart-bar-right {
      .total-price-title {
        color: #ff6700;
        font-size: 14px;
      }
      .total-price {
        color: #ff6700;
        font-size: 30px;
      }
      .btn-primary {
        cursor: pointer;
        border: none;
        float: right;
        width: 200px;
        height: 50px;
        text-align: center;
        font-size: 18px;
        margin-left: 50px;
        background: #ff6700;
        color: #fff;
      }
      .btn-primary-disabled {
        background: #ffb787;
      }
    }
  }
}
.mb20 {
  height: 20px;
}
</style>